package algorithms.implementation

/**
 * [Forming a Magic Square](https://www.hackerrank.com/challenges/magic-square-forming)
 */
// Complete the formingMagicSquare function below.
fun formingMagicSquare(s: Array<Array<Int>>): Int {
    val availableDigits = arrayOf(1, 2, 3, 4, 6, 7, 8, 9)
    fun enumMagicSquares(): MutableList<Array<Array<Int>>> {
        val result = mutableListOf<Array<Array<Int>>>()
        for (a in availableDigits) {
            val leftA = availableDigits.filter { !(it == a || it + a == 10) }
            for (b in leftA) {
                if (a + b < 6 || a + b > 15) {
                    continue
                }
                val leftB = leftA.filter { !(it == b || it + b == 10) }
                val c = 15 - a - b
                if (leftB.contains(c)) {
                    val leftC = leftB.filter { !(it == c || it + c == 10) }
                    val d = 5 - a + c
                    if (leftC.contains(d)) {
                        result.add(
                            arrayOf(
                                arrayOf(a, b, c),
                                arrayOf(d, 5, 10 - d),
                                arrayOf(10 - c, 10 - b, 10 - a)
                            )
                        )
                    }
                }
            }
        }
        return result
    }

    val costs = mutableListOf<Int>()
    var temp: Int
    for (magicSquare in enumMagicSquares()) {
        temp = 0
        for (i in 0..2) {
            for (j in 0..2) {
                temp += kotlin.math.abs(magicSquare[i][j] - s[i][j])
            }
        }
        costs.add(temp)
    }
    return costs.min()!!
}